/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 *
 * @author Borja
 */
@WebServlet(name = "index", urlPatterns = {"/index"})
public class index extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
   @Resource(name = "jdbc/Tienda_bfernandezo_asanchezoliv")
    private DataSource ds;
    private String contenido;
    private Cesta cesta = Cesta.getInstancia();
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {   
            char comillas = '"';
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
            out.println("<title>En ca' Paqui</title>");
            out.println("<link href='styles/styles.css' rel='stylesheet' type='text/css'>");
            out.println("<script src='scripts/jquery-1.7.js' type='text/javascript'></script>");
            out.println("<script src='scripts/general.js' type='text/javascript'></script>  ");
            out.println("        <script>");
            out.println("$(document).ready(function() {");
            out.println("        $('#texto').bind('keypress', function(event){");
            out.println("        var opcion = $('#tipo option:selected').html();");
            out.println("        if (opcion == 'Precio') {");
            out.println("            if ( (  (event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 13) && (event.keyCode != 46))");
            out.println("                return false;");
            out.println("        }");
            out.println("    });");
            out.println("});");
            out.println("function mostrarOperador(){");
            out.println("    var opcion = $('#tipo option:selected').html();");
            out.println("        if (opcion == 'Precio') ");
            out.println("            $('#operador').css('display','initial');");
            out.println("        else");
            out.println("            $('#operador').css('display','none');");
            out.println("        }");
            out.println("</script>");
            out.println("  </head>");
            out.println("  <body>");
            out.println("          <a id='titulo' href='/Tienda_bfernandezo_asanchezoliv'><h1 id='titulo'>Tienda virtual "+comillas+"En ca' Paqui"+comillas+"</h1></a>");
            out.println("          <div class='cesta'>");
            out.println(" <span><a href='cesta.jsp' id='txtNegro'> Cesta: </span><span><b>"+cesta.getTamanoCesta()+"</b></span><span> artículo/s | </span></a> <a href='Login'> Loguearse </a>");
            out.println("          </div>");
            out.println("          <div class='superior'>");
            out.println("              <div class='categoria'>");
            out.println("                  <b>Categoría</b>");
            out.println("                  <form name='Categoria' action='categoria'>        ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=1'>Alimentación</a> </p>");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=2'>Droguería</a> </p>              ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=3'>Prensa</a> </p>               ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=4'>Herramientas</a>  </p>    ");
            out.println("                  </form>");
            out.println("              </div>");
            out.println("              ");
            out.println("              <div class='busqueda'>  ");
            out.println("                  <form name='Busqueda' action='index' method='get' class='formBusqueda'>");    
            out.println("                      <b>Busqueda</b> ");
            out.println("                      <select id='tipo' name='t' size='1' onchange="+comillas+"$('#texto').attr('value','');mostrarOperador();"+comillas+">");
            out.println("                          <option name='t' value='2'>Nombre</option>");
            out.println("                          <option name='t' value='3'>Precio</option>");
            out.println("                       </select>");
            out.println("                       <select class='operador' id='operador' name='operador' size='1'>");
            out.println("                           <option value='1'>menor que</option>");
            out.println("                           <option value='2'>menor igual que</option>");
            out.println("                           <option value='3'>igual que</option>");
            out.println("                           <option value='4'>mayor o igual que</option>");
            out.println("                           <option value='5'>mayor que</option>");                            
            out.println("                       </select>");
            out.println("                       <input id='texto'type='text' name='texto' value='' />");
            out.println("                       <input type='submit' value='Ir' name='Ir' />");
            out.println("                  </form>");out.println("               </div>");
            out.println("           </div>");
            out.println("            <div class='contenido'>");
            out.println(contenido);
            out.println("        </div>");
            out.println("</body>");
            out.println("</html>");
            
            /*
            out.println("<html>");
            out.println("<head>");
            out.println("<title>"+producto.getNombre()+"</title>");  
            out.println("<script src='scripts/jquery-1.7.js'></script>");
            out.println("<link href='styles/styles.css' rel='stylesheet' type='text/css'>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>"+producto.getNombre()+"</h1>");
            out.println("<h3>Description: <a>"+producto.getDescripcion()+"</a></h3>");
            out.println("<h3>Precio: <a>"+producto.getPrecio()+" €</a></h3>");
            out.println("<h3>Stock: <a>"+producto.getStock()+" unidades</a></h3>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="uncollapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Producto[] productos = null;
        try {
            int opcion;
            contenido = "";
            Tienda tienda = Tienda.getInstancia(ds);                        
            String parametros ="?";
            try{
                opcion = Integer.parseInt(request.getParameter("t"));
            }catch(Exception e){
                try{
                    String aux = request.getParameter("t");    
                    if (aux =="Nombre")
                        opcion = 2;
                    else if (aux == "Precio")
                        opcion = 3;
                    else
                        opcion = -1;
                    
                }catch(Exception e2){
                    opcion = -1;                
                }
            }
            if (opcion != -1)
                parametros += "t=" + opcion;    
            
            switch(opcion){
                case 1: 
                     try{
                        int idFamilia = Integer.parseInt(request.getParameter("categoria"));
                        parametros += "&categoria=" + idFamilia;    
                        productos = tienda.recogerProductoPorCategoria(idFamilia);
                     }catch(Exception e){System.out.println(e.getMessage());}
                    break;
                case 2: 
                        try {
                            String nombre = request.getParameter("texto");
                            parametros += "&texto=" + nombre; 
                            nombre = "%" + nombre + "%"; 
                            productos = tienda.recogerProductoPorNombre(nombre);
                        }catch(Exception e){System.out.println(e.getMessage());}
                        
                    break;                    
                case 3: 
                       try {
                            int operadorAux = Integer.parseInt(request.getParameter("operador"));
                            float precio = Float.parseFloat(request.getParameter("texto"));
                            parametros += "&texto=" + String.valueOf(precio).trim() + "&operador=" +  String.valueOf(operadorAux).trim();  
                            String operador = "=";
                            switch(operadorAux){
                                case 1:
                                    operador = "<";
                                    break;
                                case 2:
                                    operador = "<=";
                                    break;
                                case 3:
                                    operador = "=";
                                    break;
                                case 4:
                                    operador = ">=";
                                    break;
                                case 5:
                                    operador = ">";
                                    break;
                            }
                            productos = tienda.recogerProductoPorPrecio(precio, operador);
                        }catch(Exception e){System.out.println(e.getMessage());}
                        
                    break;                     
            }
            char comillas = '"';
            
            try{
                int c = Integer.parseInt(request.getParameter("c")); /*Si no da error es que vamos a añadir a la cesta. Con error, es que c=1 no existe */
                /*Añadir*/
                int f = Integer.parseInt(request.getParameter("f"));
                int p = Integer.parseInt(request.getParameter("p"));
                Producto producto = tienda.recogerProductoPorId(p,f);
                cesta.añadirProducto(producto, 1);
                
                /* Fin añadir*/
                String redirect = request.getRequestURI() + parametros;
                response.sendRedirect(redirect);
            }catch(Exception e){}
            
            try{
                for (Producto producto:productos){
                            contenido +="<div class='producto'>";
                            contenido +="<span>"+producto.getNombre()+"</span>";
                            contenido +="<br />";
                            contenido +="<img src='"+producto.getImagen()+"'class='imagenProducto'>";
                            contenido +="<br />";
                            contenido +="<div class='infoProducto'>";
                            contenido +="<span class='precio'>"+producto.getPrecio()+" € ";
                            contenido +="<input type='submit' value='Añadir a la cesta' name='"
                                    +producto.getIdFamilia()+","
                                    +producto.getIdProducto()+"' onclick='javascript:window.location.replace("+ comillas +"/Tienda_bfernandezo_asanchezoliv/index"
                                    + parametros + "&c=1" 
                                    + "&f=" + producto.getIdFamilia()
                                    + "&p=" + producto.getIdProducto()+ comillas +")'/>";
                            contenido +="</div></div>";
                            
                        }
            }catch(Exception e){System.out.println(e.getMessage());}
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(index.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(index.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}